#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc
import djangoproject.models.ipbase
import COOPIP_Form, COOPIP_FormGeneral, COOPIP_FormRevenueProtection, COOPIP_FormIntranet, COOPIP_FormNetworkDevice
import reportlab
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import mm
from reportlab.graphics.barcode import code128
import CIS, GIS



def BuildTestHarnessForm():
    from django.contrib import admin
    Dict={}
    Dict['GetLatestReadingByMeterNoIndicator']=forms.BooleanField(required=False)
    Dict['InitiateMeterReadByMeterNoAndTypeIndicator']=forms.BooleanField(required=False)
    Dict['GetSupportedReadingTypesIndicator']=forms.BooleanField(required=False)
    Dict['MeterNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessTestHarnessForm(form, UserName):
    DataSent = []
    ResponseReceived = []
    TimeLogs = []

    GetLatestReadingByMeterNoIndicator=COOPIP_Form.FormGetBoolean(form, 'GetLatestReadingByMeterNoIndicator')
    InitiateMeterReadByMeterNoAndTypeIndicator=COOPIP_Form.FormGetBoolean(form, 'InitiateMeterReadByMeterNoAndTypeIndicator')
    GetSupportedReadingTypesIndicator=COOPIP_Form.FormGetBoolean(form, 'GetSupportedReadingTypesIndicator')

    MeterNumber=str(COOPIP_Form.FormGetInteger(form, 'MeterNumber')) #Convert to Int, then string to ensure only integer values are accepted
    if(GetLatestReadingByMeterNoIndicator):
        djangoproject.models.cooptalk.COOPTalk.OutGetMeterReadByMeterNumber(MeterNumber)
        StartTime = datetime.datetime.now()
        djangoproject.models.cooptalk.COOPTalk.SendAllOut()
        CompleteTime = datetime.datetime.now()
        TimeLogs.append( str((CompleteTime-StartTime).total_seconds()) + ' seconds  Start Time:  ' + str(StartTime) + '  End Time:  ' + str(CompleteTime))

        LatestCOOPTalk = djangoproject.models.cooptalk.COOPTalk.objects.all().order_by('-id')[0]
        DataSent.append(LatestCOOPTalk.ConnectionString + '\n\n' + LatestCOOPTalk.Header + '\n\n' + LatestCOOPTalk.Body + '\n\n')
        ResponseReceived.append(LatestCOOPTalk.Response)
    elif(InitiateMeterReadByMeterNoAndTypeIndicator):
        djangoproject.models.cooptalk.COOPTalk.OutInitiateMeterReadByMeterNumberAndType(MeterNumber)
        StartTime = datetime.datetime.now()
        djangoproject.models.cooptalk.COOPTalk.SendAllOut()
        CompleteTime = datetime.datetime.now()
        TimeLogs.append( str((CompleteTime-StartTime).total_seconds()) + ' seconds  Start Time:  ' + str(StartTime) + '  End Time:  ' + str(CompleteTime))

        LatestCOOPTalk = djangoproject.models.cooptalk.COOPTalk.objects.all().filter(CreateDateTime__lte=StartTime).order_by('-id')[0]
        DataSent.append(str(LatestCOOPTalk.ConnectionString) + '\n\n' + str(LatestCOOPTalk.Header) + '\n\n' + str(LatestCOOPTalk.Body) + '\n\n')
        ResponseReceived.append(LatestCOOPTalk.Response)
    elif(GetSupportedReadingTypesIndicator):
        djangoproject.models.cooptalk.COOPTalk.OutGetSupportedReadingTypes()
        StartTime = datetime.datetime.now()
        djangoproject.models.cooptalk.COOPTalk.SendAllOut()
        CompleteTime = datetime.datetime.now()
        TimeLogs.append( str((CompleteTime-StartTime).total_seconds()) + ' seconds  Start Time:  ' + str(StartTime) + '  End Time:  ' + str(CompleteTime))
        LatestCOOPTalk = djangoproject.models.cooptalk.COOPTalk.objects.all().filter(CreateDateTime__lte=StartTime).order_by('-id')[0]
        DataSent.append(str(LatestCOOPTalk.ConnectionString) + '\n\n' + str(LatestCOOPTalk.Header) + '\n\n' + str(LatestCOOPTalk.Body) + '\n\n')
        ResponseReceived.append(LatestCOOPTalk.Response)
 
    return '\n'.join(TimeLogs), '\n'.join(DataSent), '\n'.join(ResponseReceived)


def PopulateTestHarnessForm(form):
    form.setData({'GetLatestReadingByMeterNoIndicator': False})
    form.setData({'InitiateMeterReadByMeterNoAndTypeIndicator':False})
    form.setData({'GetSupportedReadingTypesIndicator':False})
    return form






